package edu.arizona.arid.akshen;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.io.file.FileSystemRegistry;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;

import edu.arizona.arid.akshen.view.ImageView;

public class PictureUploader extends MIDlet implements CommandListener {
	private Display display;
	private Form form;
	
	private String currDirName;

	private Command view = new Command("View", Command.ITEM, 1);
	private Command back = new Command("Back", Command.BACK, 2);
	private Command exit = new Command("Exit", Command.EXIT, 3);

	private final static String UP_DIRECTORY = "..";
	private final static String MEGA_ROOT = "/";
	private final static String SEP_STR = "/";
	private final static char SEP = '/';
	
	private ChoiceGroup radioButtons = new ChoiceGroup("Select Your Color", Choice.EXCLUSIVE);

	public PictureUploader() {
		currDirName = MEGA_ROOT;
	}

	public void startApp() {
		display = Display.getDisplay(this);
		form = new Form("Akshen!");
		display.setCurrent(form);
		
		boolean isAPIAvailable = false;
		if (System.getProperty("microedition.io.file.FileConnection.version") != null) {
			isAPIAvailable = true;
			try {
				showCurrDir();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			StringBuffer splashText = new StringBuffer(
					getAppProperty("MIDlet-Name")).append("\n").append(
					getAppProperty("MIDlet-Vendor")).append(
					isAPIAvailable ? "" : "\nFileConnection API not available");
			Alert splashScreen = new Alert(null, splashText.toString(), null,
					AlertType.INFO);
			splashScreen.setTimeout(3000);
			display.setCurrent(splashScreen);
		}

	}

	public void pauseApp() {
	}

	public void destroyApp(boolean cond) {
		notifyDestroyed();
	}

	public void commandAction(Command c, Displayable d) {
		if (c == view) {
			List curr = (List) d;
			final String currFile = curr.getString(curr.getSelectedIndex());
			new Thread(new Runnable() {
				public void run() {
					if (currFile.endsWith(SEP_STR)
							|| currFile.equals(UP_DIRECTORY)) {
						traverseDirectory(currFile);
					} else {
						showFile(currFile);
					}
				}
			}).start();
		} else if (c == back) {
			showCurrDir();
		} else if (c == exit) {
			destroyApp(false);
		}
		
	}

	private void showCurrDir() {
		Enumeration e;
		FileConnection currDir = null;
		List browser;
		try {
			if (MEGA_ROOT.equals(currDirName)) {
				e = FileSystemRegistry.listRoots();
				browser = new List(currDirName, List.IMPLICIT);
			} else {
				currDir = (FileConnection) Connector.open("file://localhost/"
						+ currDirName);
				e = currDir.list();
				browser = new List(currDirName, List.IMPLICIT);
				browser.append(UP_DIRECTORY, null);
			}
			while (e.hasMoreElements()) {
				String fileName = (String) e.nextElement();
				if (fileName.charAt(fileName.length() - 1) == SEP) {
					browser.append(fileName, null);
				} else {
					browser.append(fileName, null);
				}
			}
			browser.setSelectCommand(view);
			browser.addCommand(exit);
			browser.setCommandListener(this);
			if (currDir != null) {
				currDir.close();
			}
			display.setCurrent(browser);
		} catch (IOException ioe) {
		}
	}

	private void traverseDirectory(String fileName) {
		if (currDirName.equals(MEGA_ROOT)) {
			if (fileName.equals(UP_DIRECTORY)) {
				// can not go up from MEGA_ROOT
				return;
			}
			currDirName = fileName;
		} else if (fileName.equals(UP_DIRECTORY)) {
			// Go up one directory
			// TODO use setFileConnection when implemented
			int i = currDirName.lastIndexOf(SEP, currDirName.length() - 2);
			if (i != -1) {
				currDirName = currDirName.substring(0, i + 1);
			} else {
				currDirName = MEGA_ROOT;
			}
		} else {
			currDirName = currDirName + fileName;
		}
		showCurrDir();
	}

	private void showFile(String fileName) {
		try {
			FileConnection fc = (FileConnection) Connector
					.open("file://localhost/" + currDirName + fileName);
			if (!fc.exists()) {
				throw new IOException("File does not exists");
			}
			
			if(fileName.endsWith("jpg")) {
				System.out.println("Viewing JPG image");
				//ImageView imageView = new ImageView();
				//imageView.setImage(Image.createImage(fc.openInputStream()));
				Image image = Image.createImage(fc.openInputStream());
				form.append(ImageView.resizeImage(image, 230, 160));
				
				radioButtons.append("Liked it", null);
				radioButtons.append("Didn't like it", null);
				form.append(radioButtons);
				
				form.addCommand(new Command("Submit", Command.OK, 1));
				form.addCommand(new Command("Discard", Command.BACK, 2));
				form.setCommandListener(this);
				
				display.setCurrent(form);
			}
			else {
				System.out.println("Viewing some file");
				InputStream fis = fc.openInputStream();
				byte[] b = new byte[1024];
				int length = fis.read(b, 0, 1024);
				fis.close();
				fc.close();
				
				TextBox tb = new TextBox("View File: " + fileName, null, 1024,
					TextField.ANY | TextField.UNEDITABLE);
			
				tb.addCommand(back);
				tb.addCommand(exit);
				tb.setCommandListener(this);

				if (length > 0) {
					tb.setString(new String(b, 0, length));
				}
				display.setCurrent(tb);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}